<?php

namespace app;
/**
 * 请求参数封装,过滤
 */
class Request extends \support\Request
{
    public function get($name = null, $default = null, $verif = null)
    {
        $value = $this->filter(parent::get($name, $default));
        if ($value == '' && $default) $value = $default;
        return $verif ? $verif($value) : $value;
    }

    public function post($name = null, $default = null, $verif = null)
    {
        $value = $this->filter(parent::post($name, $default));
        if ($value == '' && $default) $value = $default;
        return $verif ? $verif($value) : $value;
    }

    public function param($name = null, $default = null, $verif = null)
    {
        if (request()->method() == 'POST') {
            $value = $this->filter(parent::post($name, $default));
        } elseif (request()->method() == 'GET') {
            $value = $this->filter(parent::get($name, $default));
        }
        if ($value == '' && $default) $value = $default;
        return $verif ? $verif($value) : $value;
    }

    public function filter($value)
    {
        if (!$value) {
            return $value;
        }
        if (is_array($value)) {
            // 如果有富文本 字段为content,editor等字段时 不过滤
            if (isset($value['content'])) {
                $field = 'content';
            }
            if (isset($value['editor'])) {
                $field = 'editor';
            }
            if (isset($field)) {
                $content = $value[$field];
                unset($value[$field]);
            }
            // 过滤字段
            array_walk_recursive($value, function(&$item){
                if (is_string($item)) {
                    $item = trim(htmlentities($item,ENT_QUOTES,"UTF-8"));
                }
            });
            if (isset($field) && isset($content)) {
                $value[$field] = $content;
            }
        } else {
            $value = trim(htmlentities($value,ENT_QUOTES,"UTF-8"));
        }
        return $value;
    }
}
